package com.attilax.sql;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import aaaDbManager.DbMetaService;

import com.attilax.collection.listUtil;
import com.attilax.jql.DataTypeUnicomMysql;
import com.attilax.linq.LinqBuilder;

import static com.attilax.linq.LinqBuilder4List.*;

import com.google.inject.Inject;

 

public class SqlKvUtil {
	
	public static void main(String[] args) {
		System.out.println("");
	}
	
	
	private String gene_vals4sql() {
		String r = "";
		for (String c : cols) {
			String colType ="varchar";// (String) colTypeMap.get(c);
			//r = r + "," + getVal(c, kvMap, colType);
			r = r + "," + getVal(c, kvMap, colType)+"";
		}
	 
		return r.substring(1);
	 
	}

	private String getVal(String c, Map<String, Object> kvMap2, String colType) {
		String type = (String) new DataTypeUnicomMysql().typeMap.get(colType);
		if ( type!=null && type.equals("num"))
			return (String) kvMap2.get(c);
		else
			return "'" +  kvMap2.get(c).toString() + "'";
	}
	String cols4sql;
	String vals4sql;
	List<String> cols = new ArrayList<String>();
	List<String> valsArr = new ArrayList<String>();
	String prikey;
	@Inject
	DbMetaService metaSvr;
	public String[] toInsertSqlKVPart(Map<String,Object> req_flted) {
		
		
		this.kvMap = req_flted;
		for (String key : req_flted.keySet()) {
			if(isAutoIncreamKey(key))
				continue;
		
			cols.add(key);
			valsArr.add(req_flted.get(key).toString());
			// System.out.println("key= "+ key + " and value= " + map.get(key));
		}
		cols4sql = listUtil.join(cols, ",");

		vals4sql = gene_vals4sql();
	String[] a=new String[2];
	a[0]=cols4sql;
	a[1]=vals4sql;return a;
		
	}
		
		private boolean isAutoIncreamKey(String key) {
			//  prikey = metaSvr.getPrimaryKey(req);
		
			@SuppressWarnings("rawtypes")
			Map row= from(ColumnsDefs).where(eq("COLUMN_NAME", key)).exe().get(0);
		return row.get("IS_AUTOINCREMENT").toString().trim().toLowerCase().equals("yes");
	}

		public String toUpSqlKvPart(Map<String,Object> req_flted) {
			
			String s="";
			this.kvMap = req_flted;
			for (String key : req_flted.keySet()) {
				if(isAutoIncreamKey(key))
					continue;
			
				//cols.add(key);
				s=s+",`"+key+"`='"+req_flted.get(key).toString()+"'";
				//valsArr.add();
				// System.out.println("key= "+ key + " and value= " + map.get(key));
			}
			return s.substring(1);
			
		}
		

		Map<String, Object> kvMap;
		public List<Map> ColumnsDefs;

		private void calc_cols4sql_n_valsArr(Map<String, Object> req_flted) {
			this.kvMap = req_flted;
			for (String key : req_flted.keySet()) {
				if(key.equals(this.prikey))
					continue;
				cols.add(key);
				valsArr.add(req_flted.get(key).toString());
				// System.out.println("key= "+ key + " and value= " + map.get(key));
			}
			cols4sql = listUtil.join(cols, ",");

			vals4sql = gene_vals4sql();

		}
	}

 
